//
//  MeView.swift
//  ezyform
//
//  Created by MoennigQ on 18/02/2017.
//  Copyright © 2017 Client.Solution Pty Ltd. All rights reserved.
//

import UIKit
import SnapKit
import RxSwift
import RxCocoa
import SDWebImage
import Alamofire
import AlamofireImage
class MeView: View {
    fileprivate lazy var disposeBag = DisposeBag()
    var dataObserver: BehaviorRelay<[MeMenuType]> = BehaviorRelay(value: [])
    let closeBtn = UIButton()
    let scrollView = DIYScrollView()
    //avatar
    let avatarImageView = UIImageView()
    //
    let helloLabel = ContentLabel(R.font.interMedium(size: 16))
    //
    let cecAccNoLabel = ContentLabel(R.font.interRegular(size: 13))
    //
    let ceclicenseLabel = ContentLabel(R.font.interRegular(size: 13))
    //
    var installingJobsCntLabel: BaseLabel!
    var completedJobCntLabel: BaseLabel!
    var currentPointsLabel: BaseLabel!
    
    //Menu
    var tableView = UITableView()
    //
    var tableViewHeightConstaint: Constraint?
    override func setUpView() {
        self.backgroundColor = .clear
        
        scrollView.drawCorner(byRoundingCorners: [.topLeft,.topRight])
        scrollView.backgroundColor = .white
        self.addSubview(scrollView)
        scrollView.snp.makeConstraints { (make) in
            make.top.equalTo(self.safeAreaLayoutGuide.snp.top).offset(APPConfig.ModelVCTopMargin)//用于模拟model弹出框的间隔，解决model vc和手势滑动冲突的问题
            make.left.right.bottom.equalTo(self)
        }
        let contentView = UIView()
        contentView.backgroundColor = .clear
        scrollView.addSubview(contentView)
        
        contentView.snp.makeConstraints { (make) in
            make.top.bottom.equalTo(scrollView)
            make.left.right.equalTo(self)
            make.height.greaterThanOrEqualTo(0)
        }
        //top back View
        let topBackView = View()
        topBackView.drawCorner(byRoundingCorners: [.topLeft,.topRight])
        contentView.addSubview(topBackView)
        topBackView.snp.makeConstraints { make in
            make.top.left.right.equalToSuperview()
            make.height.greaterThanOrEqualTo(0)
        }
        //
        //avatarImageView
        avatarImageView.layer.cornerRadius = 25
        avatarImageView.clipsToBounds = true
        avatarImageView.contentMode = .scaleToFill
        topBackView.addSubview(avatarImageView)
        avatarImageView.snp.makeConstraints { make in
            make.top.equalTo(24)
            make.left.equalTo(20)
            make.width.height.equalTo(50)
        }
        //avatarModifyImageView
        let avatarModifyImageView = UIImageView(image: R.image.me_avater_modify_icon())
        topBackView.addSubview(avatarModifyImageView)
        avatarModifyImageView.snp.makeConstraints { make in
            make.bottom.right.equalTo(avatarImageView)
            make.width.height.equalTo(20)
        }
        //helloLabel, cec accNo
        let helloStackView = UIStackView(arrangedSubviews: [helloLabel,cecAccNoLabel,ceclicenseLabel])
        helloStackView.axis = .vertical
        helloStackView.distribution = .fillProportionally//根据每个子视图里面内容的尺寸来进行填充操作
        helloStackView.spacing = 2
        topBackView.addSubview(helloStackView)
        helloStackView.snp.makeConstraints { (make) in
            make.centerY.equalTo(avatarImageView)
            make.left.equalTo(avatarImageView.snp.right).offset(12)
            make.width.height.greaterThanOrEqualTo(0)
        }
        //close btn
        closeBtn.setImage(R.image.me_presentvc_close(), for: UIControl.State.normal)
        topBackView.addSubview(closeBtn)
        closeBtn.snp.makeConstraints { make in
            make.centerY.equalTo(avatarImageView)
            make.right.equalTo(-8)
            make.width.height.equalTo(40)
        }
        //****installing jobs, complete jobs, current points的宽度
        let jobsLabelWidth = (APPConfig.WidthForPortrait - Constant.LeftRightMargin * 2) / 3
        let jobsBackView = UIView()
        jobsBackView.backgroundColor = .white
        topBackView.addSubview(jobsBackView)
        jobsBackView.snp.makeConstraints { make in
            make.top.equalTo(avatarImageView.snp.bottom).offset(20)
            make.left.equalTo(Constant.LeftRightMargin)
            make.right.equalTo(-Constant.LeftRightMargin)
            make.height.greaterThanOrEqualTo(0)
            make.bottom.equalToSuperview()
        }
        //installingJobs
        installingJobsCntLabel = self.generateJobsContent()
        jobsBackView.addSubview(installingJobsCntLabel)
        installingJobsCntLabel.snp.makeConstraints { make in
            make.left.top.equalToSuperview()
            make.width.equalTo(jobsLabelWidth)
            make.height.greaterThanOrEqualTo(0)
        }
        let installingJobsCntTitle = self.generateJobsTitle(R.string.localizable.installingJobs())
        jobsBackView.addSubview(installingJobsCntTitle)
        installingJobsCntTitle.snp.makeConstraints { make in
            make.left.equalToSuperview()
            make.top.equalTo(installingJobsCntLabel.snp.bottom).offset(8)
            make.width.equalTo(jobsLabelWidth)
            make.height.greaterThanOrEqualTo(0)
        }
        //vertialLineView
        let vertialLineView1 = View(hexStr: Constant.SeparatorColorHexStr)
        jobsBackView.addSubview(vertialLineView1)
        vertialLineView1.snp.makeConstraints { make in
            make.width.equalTo(1)
            make.height.equalTo(24)
            make.left.equalTo(installingJobsCntTitle.snp.right)
            make.centerY.equalToSuperview()
        }
        //completedJobCntLabel
        completedJobCntLabel = self.generateJobsContent()
        jobsBackView.addSubview(completedJobCntLabel)
        completedJobCntLabel.snp.makeConstraints { make in
            make.centerX.equalToSuperview()
            make.top.equalTo(installingJobsCntLabel)
            make.width.equalTo(jobsLabelWidth)
            make.height.greaterThanOrEqualTo(installingJobsCntLabel)
        }
        let completedJobCntTitle = self.generateJobsTitle(R.string.localizable.completedJobs())
        jobsBackView.addSubview(completedJobCntTitle)
        completedJobCntTitle.snp.makeConstraints { make in
            make.centerX.equalToSuperview()
            make.width.equalTo(jobsLabelWidth-8)
            make.height.equalTo(installingJobsCntTitle)
            make.centerY.equalTo(installingJobsCntTitle)
            make.bottom.equalTo(-Constant.AllOutMargin)
        }
        //vertialLineView
        let vertialLineView2 = View(hexStr: Constant.SeparatorColorHexStr)
        jobsBackView.addSubview(vertialLineView2)
        vertialLineView2.snp.makeConstraints { make in
            make.width.equalTo(1)
            make.height.equalTo(24)
            make.left.equalTo(completedJobCntTitle.snp.right)
            make.centerY.equalToSuperview()
        }
        //currentPointsLabel
        currentPointsLabel = self.generateJobsContent()
        jobsBackView.addSubview(currentPointsLabel)
        currentPointsLabel.snp.makeConstraints { make in
            make.right.top.equalToSuperview()
            make.width.equalTo(jobsLabelWidth)
            make.height.greaterThanOrEqualTo(installingJobsCntLabel)
        }
        let currentPointsTitle = self.generateJobsTitle(R.string.localizable.currentPoints())
        jobsBackView.addSubview(currentPointsTitle)
        currentPointsTitle.snp.makeConstraints { make in
            make.centerX.equalTo(currentPointsLabel)
            make.top.equalTo(installingJobsCntTitle)
            make.width.equalTo(jobsLabelWidth)
            make.height.equalTo(installingJobsCntTitle)
        }
        //
        let horitalLineView = View(hexStr: Constant.SeparatorColorHexStr)
        contentView.addSubview(horitalLineView)
        horitalLineView.snp.makeConstraints { make in
            make.top.equalTo(topBackView.snp.bottom).offset(16)
            make.height.equalTo(1)
            make.left.right.equalToSuperview()
        }
        //table view
        tableView.register(MeTableViewCell.self, forCellReuseIdentifier: MeTableViewCell.reuseCellIdentifier)
        tableView.separatorStyle = UITableViewCell.SeparatorStyle.none
        tableView.backgroundColor = UIColor.clear
        tableView.isScrollEnabled = false
        tableView.showsVerticalScrollIndicator = false
        contentView.addSubview(tableView)
        tableView.snp.makeConstraints { (make) in
            make.top.equalTo(horitalLineView.snp.bottom)
            make.left.right.equalToSuperview()
            self.tableViewHeightConstaint = make.height.greaterThanOrEqualTo(0).constraint
        }
        //
        let copyRightView = MeCopyRightView()
        contentView.addSubview(copyRightView)
        copyRightView.snp.makeConstraints { (make) in
            make.top.equalTo(tableView.snp.bottom).offset(20)
            make.left.equalTo(Constant.LeftRightMargin)
            make.right.equalTo(-Constant.LeftRightMargin)
            make.height.greaterThanOrEqualTo(0)
            make.bottom.equalTo(-Constant.AllOutMargin)
        }
        //
        //设置cell信息，绑定数据源
        dataObserver.bind(to: tableView.rx.items(cellIdentifier: MeTableViewCell.reuseCellIdentifier,cellType: MeTableViewCell.self)){(row, model, cell) in
            cell.setData(model)
        }.disposed(by: self.disposeBag)
        //监听tableview的高度
        tableView.rx.observe(CGSize.self,"contentSize").subscribe {[weak self] (size) in
            guard let contentSize = size else {return}
            self?.tableViewHeightConstaint?.update(offset: contentSize.height)
        }.disposed(by: self.disposeBag)
        //默认头像
        self.avatarImageView.image = R.image.me_default_avatar()
        //
        APPConfig.loginInfo.rx.observe(String.self, "avatarURLStr").subscribe { [weak self] urlStr in
            self?.setAvatarImage()
        }.disposed(by: self.disposeBag)
    }
    private func setAvatarImage(){
        //设置头像
        SDWebImageManager.shared().imageCache?.clearMemory()//先清空内存缓存
        if let url = URL(string: APPConfig.loginInfo.avatarURLStr){
            self.avatarImageView.sd_setImage(with: url,placeholderImage: R.image.me_default_avatar(),options: SDWebImageOptions.cacheMemoryOnly)
        }else{
            self.avatarImageView.image = R.image.me_default_avatar()
        }
        
    }
    func setData(){
        self.helloLabel.text = "Hi,\(APPConfig.loginInfo.fullName )"
        
        if APPConfig.loginInfo.installer || APPConfig.loginInfo.designer {
            self.cecAccNoLabel.isHidden = false
            var resultStr = ""
            /// 2024-03-02 edit
            if XpTools.isGreaterThanOverTime() == true { // 失效
                resultStr = "SAA No.: \(APPConfig.loginInfo.saaNumber)"
            }else{
                if APPConfig.loginInfo.saaNumber != "" {
                    resultStr = "SAA No.: \(APPConfig.loginInfo.saaNumber)"
                }else{
                    resultStr = "CEC Acc No.: \(APPConfig.loginInfo.accreditedNumber)"
                }
            }
            self.cecAccNoLabel.text = resultStr
        }else {
            self.cecAccNoLabel.isHidden = true
        }
        
        self.ceclicenseLabel.isHidden = !APPConfig.loginInfo.plumber
        self.ceclicenseLabel.text = "Plumber licence: \(APPConfig.loginInfo.plumber_licenses)"
        
    }
    
    
    func setJobsCntAndReward(_ model: JobsCntAndReward){
        self.installingJobsCntLabel.text = Tool().formatAmountToStr(amount: "\(model.installing ?? 0)", maximumFractionDigits: 0,minimumFractionDigits: 0)
        self.completedJobCntLabel.text = Tool().formatAmountToStr(amount: "\(model.installed ?? 0)", maximumFractionDigits: 0,minimumFractionDigits: 0)
        self.currentPointsLabel.text = Tool().formatAmountToStr(amount: "\(model.reward ?? 0)", maximumFractionDigits: 0,minimumFractionDigits: 0)
    }
    private func generateJobsTitle(_ text: String)->BaseLabel{
        let view = BaseLabel()
        view.text = text
        view.textColor = UIColor(hexStr: "#292D32")
        view.setFont(R.font.interMedium(size: 11))
        view.textAlignment = .center
        view.numberOfLines = 0
        view.lineBreakMode = .byWordWrapping
        return view
    }
    private func generateJobsContent()->BaseLabel{
        let view = BaseLabel()
        view.textColor = UIColor(hexStr: "#379657")
        view.setFont(R.font.lexendBold(size: 20))//R.font.dinAlternateBold(size: 20)
        view.textAlignment = .center
        view.numberOfLines = 2
        return view
    }
}


class XpTools : NSObject {
    
    /// 用于判断当前时间是否大于 2024-05-30
    /// - Returns: true ass 生效
    class func isGreaterThanOverTime() -> Bool {
        var isOverTime = false
        
        let currentDate = Date()
        
        let overTimeString = "2024-05-29 23:59:59"
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss" // 根据实际情况修改日期格式
        let overTimeDate = dateFormatter.date(from: overTimeString)
        
        if let result = overTimeDate?.compare(currentDate) {
            if result == .orderedAscending { /// 当前时间大于时间 -> 失效
                isOverTime = true
            }
            
        }
        return isOverTime
    }
}
